package controller;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.NewsModel;
import model.TagModel;
import entity.News;
import entity.Tag;

/**
 * Servlet implementation class NewsTag
 */
@WebServlet("/NewsTag")
public class NewsTag extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		response.setContentType("text/html;charset=UTF-8");
        String url = request.getRequestURI();
        String[] splitUrl = url.split("/");
        String tagAlias = splitUrl[splitUrl.length-1];
        NewsModel newsModel = new NewsModel();
        TagModel tagModel = new TagModel();
        Tag tag = tagModel.findByAlias(tagAlias);
        if (!tag.getAlias().equalsIgnoreCase("")) {
        	List<News> listNews = newsModel.findByTag(tag.getAlias());
            request.setAttribute("listNews", listNews); 
            request.setAttribute("tag", tagAlias); 
            request.getRequestDispatcher("/tag.jsp").forward(request, response);
        } else {
        	response.sendRedirect("/home.jsp");
        }        
	}

}
